﻿using System.Security.Cryptography;
using System.Text;

namespace StudyCompanion.Commons.Encrypt;

/// <summary>
///     MD5加密
/// </summary>
public class MD5Encryption
{
    /// <summary>
    ///     构造函数
    /// </summary>
    public MD5Encryption()
    {
    }

    /// <summary>
    ///     MD5 加密
    /// </summary>
    /// <param name="text">加密文本</param>
    /// <param name="uppercase">是否输出大写加密，默认 false</param>
    /// <param name="is16">是否输出16位 默认32位</param>
    /// <returns></returns>
    public static string Encrypt(string text, bool uppercase = false, bool is16 = false)
    {
        var data = MD5.HashData(Encoding.UTF8.GetBytes(text));

        var stringBuilder = new StringBuilder();
        for (var i = 0; i < data.Length; i++) stringBuilder.Append(data[i].ToString("x2"));
        var md5String = stringBuilder.ToString();
        var hash = !is16 ? md5String : md5String.Substring(8, 16);
        return !uppercase ? hash : hash.ToUpper();
    }

    /// <summary>
    ///     MD5 比较
    /// </summary>
    /// <param name="text">加密文本</param>
    /// <param name="hash">MD5 字符串</param>
    /// <param name="uppercase">是否输出大写加密，默认 false</param>
    /// <param name="is16">是否输出16位</param>
    /// <returns>bool</returns>
    public static bool Compare(string text, string hash, bool uppercase = false, bool is16 = false)
    {
        var hashOfInput = Encrypt(text, uppercase, is16);
        return hash.Equals(hashOfInput, StringComparison.OrdinalIgnoreCase);
    }
}